const mongoose = require('mongoose');
const User = require('../models/User');
const Activity = require('../models/Activity');
require('dotenv').config();

// Sample data
const sampleUsers = [
  {
    openId: 'sample_openid_1',
    unionId: 'sample_unionid_1',
    nickname: 'Alex Chen',
    avatarUrl: 'https://picsum.photos/200/200?random=1',
    gender: 1,
    bio: 'Love hiking, photography, and meeting new people! 🏔️📸',
    phone: '13800138001',
    email: 'alex@example.com',
    location: {
      province: 'Beijing',
      city: 'Beijing',
      district: 'Haidian',
      address: 'Zhongguancun',
      coordinates: {
        latitude: 39.9042,
        longitude: 116.4074
      }
    },
    preferences: {
      activityTypes: ['sports', 'travel', 'photography', 'music'],
      notificationEnabled: true,
      locationSharingEnabled: true
    }
  },
  {
    openId: 'sample_openid_2',
    unionId: 'sample_unionid_2',
    nickname: 'Sarah Wang',
    avatarUrl: 'https://picsum.photos/200/200?random=2',
    gender: 2,
    bio: 'Foodie and coffee lover ☕ Exploring the best cafes in town',
    phone: '13900139002',
    email: 'sarah@example.com',
    location: {
      province: 'Shanghai',
      city: 'Shanghai',
      district: 'Xuhui',
      address: 'Xujiahui',
      coordinates: {
        latitude: 31.2304,
        longitude: 121.4737
      }
    },
    preferences: {
      activityTypes: ['food', 'coffee', 'study', 'movie'],
      notificationEnabled: true,
      locationSharingEnabled: true
    }
  },
  {
    openId: 'sample_openid_3',
    unionId: 'sample_unionid_3',
    nickname: 'Mike Zhang',
    avatarUrl: 'https://picsum.photos/200/200?random=3',
    gender: 1,
    bio: 'Tech enthusiast and board game collector 🎲💻',
    phone: '13700137003',
    email: 'mike@example.com',
    location: {
      province: 'Guangdong',
      city: 'Shenzhen',
      district: 'Nanshan',
      address: 'Hi-Tech Park',
      coordinates: {
        latitude: 22.5431,
        longitude: 114.0579
      }
    },
    preferences: {
      activityTypes: ['gaming', 'tech', 'study', 'sports'],
      notificationEnabled: true,
      locationSharingEnabled: true
    }
  },
  {
    openId: 'sample_openid_4',
    unionId: 'sample_unionid_4',
    nickname: 'Emma Liu',
    avatarUrl: 'https://picsum.photos/200/200?random=4',
    gender: 2,
    bio: 'Yoga instructor and wellness advocate 🧘‍♀️',
    phone: '13600136004',
    email: 'emma@example.com',
    location: {
      province: 'Sichuan',
      city: 'Chengdu',
      district: 'Jinjiang',
      address: 'Chunxi Road',
      coordinates: {
        latitude: 30.5728,
        longitude: 104.0668
      }
    },
    preferences: {
      activityTypes: ['sports', 'wellness', 'food', 'travel'],
      notificationEnabled: true,
      locationSharingEnabled: true
    }
  },
  {
    openId: 'sample_openid_5',
    unionId: 'sample_unionid_5',
    nickname: 'David Li',
    avatarUrl: 'https://picsum.photos/200/200?random=5',
    gender: 1,
    bio: 'Music producer and DJ 🎵 Let\'s make some noise!',
    phone: '13500135005',
    email: 'david@example.com',
    location: {
      province: 'Beijing',
      city: 'Beijing',
      district: 'Chaoyang',
      address: 'Sanlitun',
      coordinates: {
        latitude: 39.9388,
        longitude: 116.4608
      }
    },
    preferences: {
      activityTypes: ['music', 'party', 'photography', 'gaming'],
      notificationEnabled: true,
      locationSharingEnabled: true
    }
  }
];

const sampleActivities = [
  {
    title: 'Weekend Hiking Adventure',
    description: 'Join us for an amazing hiking trip to the Great Wall! We\'ll explore the less crowded sections and enjoy breathtaking views. Perfect for photography enthusiasts and nature lovers.',
    type: 'sports',
    mainImage: 'https://picsum.photos/400/300?random=10',
    startTime: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000), // 3 days from now
    endTime: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000 + 8 * 60 * 60 * 1000), // 8 hours later
    maxParticipants: 15,
    minParticipants: 5,
    location: {
      name: 'Mutianyu Great Wall',
      address: 'Huairou District, Beijing',
      detailedAddress: 'Meet at the main entrance',
      coordinates: {
        latitude: 40.4319,
        longitude: 116.2311
      },
      city: 'Beijing',
      district: 'Huairou',
      province: 'Beijing'
    },
    requirements: {
      ageRange: { min: 18, max: 60 },
      genderRestriction: 'none',
      cost: 50,
      currency: 'CNY',
      bringItems: ['Water', 'Snacks', 'Camera', 'Comfortable shoes'],
      skills: ['Basic hiking experience']
    },
    tags: ['hiking', 'photography', 'nature', 'greatwall', 'weekend'],
    visibility: 'public'
  },
  {
    title: 'Board Game Night',
    description: 'Let\'s gather for an evening of board games! We have a collection of modern board games including Catan, Azul, Wingspan, and many more. Beginners welcome!',
    type: 'gaming',
    mainImage: 'https://picsum.photos/400/300?random=11',
    startTime: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000), // 2 days from now
    endTime: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000 + 4 * 60 * 60 * 1000), // 4 hours later
    maxParticipants: 8,
    minParticipants: 3,
    location: {
      name: 'Board Game Café',
      address: 'Xuhui District, Shanghai',
      detailedAddress: '3rd Floor, Building A, Metro City',
      coordinates: {
        latitude: 31.1933,
        longitude: 121.4368
      },
      city: 'Shanghai',
      district: 'Xuhui',
      province: 'Shanghai'
    },
    requirements: {
      ageRange: { min: 16, max: 99 },
      genderRestriction: 'none',
      cost: 30,
      currency: 'CNY',
      bringItems: ['Your enthusiasm'],
      skills: []
    },
    tags: ['boardgames', 'strategy', 'social', 'fun', 'evening'],
    visibility: 'public'
  },
  {
    title: 'Coffee Tasting Workshop',
    description: 'Discover the world of specialty coffee! We\'ll taste different beans from around the world, learn brewing techniques, and explore the art of coffee making.',
    type: 'food',
    mainImage: 'https://picsum.photos/400/300?random=12',
    startTime: new Date(Date.now() + 5 * 24 * 60 * 60 * 1000), // 5 days from now
    endTime: new Date(Date.now() + 5 * 24 * 60 * 60 * 1000 + 3 * 60 * 60 * 1000), // 3 hours later
    maxParticipants: 12,
    minParticipants: 6,
    location: {
      name: 'Artisan Coffee Roasters',
      address: 'Nanshan District, Shenzhen',
      detailedAddress: 'Shop 15, Coastal City Mall',
      coordinates: {
        latitude: 22.5074,
        longitude: 113.9316
      },
      city: 'Shenzhen',
      district: 'Nanshan',
      province: 'Guangdong'
    },
    requirements: {
      ageRange: { min: 18, max: 65 },
      genderRestriction: 'none',
      cost: 80,
      currency: 'CNY',
      bringItems: ['Notebook', 'Pen'],
      skills: []
    },
    tags: ['coffee', 'tasting', 'workshop', 'learning', 'gourmet'],
    visibility: 'public'
  },
  {
    title: 'Electronic Music Production Session',
    description: 'Learn the basics of electronic music production! We\'ll cover beat making, synthesizers, and mixing techniques. Bring your laptop and headphones!',
    type: 'music',
    mainImage: 'https://picsum.photos/400/300?random=13',
    startTime: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000), // 1 week from now
    endTime: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000 + 4 * 60 * 60 * 1000), // 4 hours later
    maxParticipants: 10,
    minParticipants: 4,
    location: {
      name: 'Music Studio',
      address: 'Chaoyang District, Beijing',
      detailedAddress: 'B1, Building 4, Sanlitun SOHO',
      coordinates: {
        latitude: 39.9378,
        longitude: 116.4472
      },
      city: 'Beijing',
      district: 'Chaoyang',
      province: 'Beijing'
    },
    requirements: {
      ageRange: { min: 16, max: 40 },
      genderRestriction: 'none',
      cost: 100,
      currency: 'CNY',
      bringItems: ['Laptop', 'Headphones'],
      skills: ['Basic computer skills']
    },
    tags: ['music', 'production', 'electronic', 'creative', 'learning'],
    visibility: 'public'
  },
  {
    title: 'Sunset Yoga in the Park',
    description: 'Join us for a relaxing yoga session in the beautiful city park. Perfect for all levels, from beginners to advanced practitioners. Connect with nature and find your inner peace.',
    type: 'sports',
    mainImage: 'https://picsum.photos/400/300?random=14',
    startTime: new Date(Date.now() + 1 * 24 * 60 * 60 * 1000), // Tomorrow
    endTime: new Date(Date.now() + 1 * 24 * 60 * 60 * 1000 + 90 * 60 * 1000), // 1.5 hours later
    maxParticipants: 20,
    minParticipants: 8,
    location: {
      name: 'People\'s Park',
      address: 'Jinjiang District, Chengdu',
      detailedAddress: 'Central lawn area near the lake',
      coordinates: {
        latitude: 30.6611,
        longitude: 104.0633
      },
      city: 'Chengdu',
      district: 'Jinjiang',
      province: 'Sichuan'
    },
    requirements: {
      ageRange: { min: 16, max: 70 },
      genderRestriction: 'none',
      cost: 0,
      currency: 'CNY',
      bringItems: ['Yoga mat', 'Water bottle', 'Towel'],
      skills: []
    },
    tags: ['yoga', 'wellness', 'outdoor', 'sunset', 'relaxation'],
    visibility: 'public'
  },
  {
    title: 'Tech Startup Networking',
    description: 'Connect with fellow entrepreneurs, developers, and investors in the tech startup ecosystem. Share ideas, find co-founders, and explore collaboration opportunities.',
    type: 'study',
    mainImage: 'https://picsum.photos/400/300?random=15',
    startTime: new Date(Date.now() + 4 * 24 * 60 * 60 * 1000), // 4 days from now
    endTime: new Date(Date.now() + 4 * 24 * 60 * 60 * 1000 + 3 * 60 * 60 * 1000), // 3 hours later
    maxParticipants: 50,
    minParticipants: 15,
    location: {
      name: 'Innovation Hub',
      address: 'Nanshan District, Shenzhen',
      detailedAddress: 'Floor 25, Tencent Building',
      coordinates: {
        latitude: 22.5431,
        longitude: 114.0579
      },
      city: 'Shenzhen',
      district: 'Nanshan',
      province: 'Guangdong'
    },
    requirements: {
      ageRange: { min: 20, max: 45 },
      genderRestriction: 'none',
      cost: 0,
      currency: 'CNY',
      bringItems: ['Business cards', 'Notebook'],
      skills: []
    },
    tags: ['networking', 'startup', 'tech', 'business', 'innovation'],
    visibility: 'public'
  }
];

const seedDatabase = async () => {
  try {
    console.log('🌱 Starting database seeding...');
    
    // Connect to database
    await mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/offline_gathering');
    console.log('✅ Connected to MongoDB');

    // Clear existing data
    await User.deleteMany({});
    await Activity.deleteMany({});
    console.log('🗑️  Cleared existing data');

    // Create users
    const createdUsers = [];
    for (const userData of sampleUsers) {
      const user = new User(userData);
      await user.save();
      createdUsers.push(user);
      console.log(`👤 Created user: ${user.nickname}`);
    }

    // Create activities and assign creators
    const createdActivities = [];
    for (let i = 0; i < sampleActivities.length; i++) {
      const activityData = sampleActivities[i];
      const creator = createdUsers[i % createdUsers.length]; // Rotate through users
      
      const activity = new Activity({
        ...activityData,
        creator: creator._id,
        participants: [{
          user: creator._id,
          status: 'joined',
          joinedAt: new Date()
        }],
        currentParticipants: 1
      });

      await activity.save();
      createdActivities.push(activity);
      console.log(`🎉 Created activity: ${activity.title}`);

      // Update user's activity count
      await User.findByIdAndUpdate(creator._id, {
        $inc: { 'statistics.activitiesCreated': 1 }
      });
    }

    // Add some participants to activities
    for (let i = 0; i < createdActivities.length; i++) {
      const activity = createdActivities[i];
      const availableUsers = createdUsers.filter(user => 
        user._id.toString() !== activity.creator.toString()
      );
      
      // Add 2-4 random participants
      const numParticipants = Math.floor(Math.random() * 3) + 2;
      const selectedParticipants = availableUsers.slice(0, numParticipants);
      
      for (const participant of selectedParticipants) {
        activity.participants.push({
          user: participant._id,
          status: 'joined',
          joinedAt: new Date()
        });
        
        // Update user's joined activity count
        await User.findByIdAndUpdate(participant._id, {
          $inc: { 'statistics.activitiesJoined': 1 }
        });
      }
      
      activity.currentParticipants = activity.participants.length;
      await activity.save();
    }

    // Create some follow relationships
    for (let i = 0; i < createdUsers.length; i++) {
      const user = createdUsers[i];
      const otherUsers = createdUsers.filter(u => u._id.toString() !== user._id.toString());
      
      // Follow 2-3 random users
      const usersToFollow = otherUsers.sort(() => 0.5 - Math.random()).slice(0, Math.floor(Math.random() * 2) + 2);
      
      for (const userToFollow of usersToFollow) {
        user.following.push(userToFollow._id);
        userToFollow.followers.push(user._id);
        
        // Check for mutual follow to become friends
        if (userToFollow.following.includes(user._id)) {
          user.friends.push(userToFollow._id);
          userToFollow.friends.push(user._id);
        }
      }
      
      await user.save();
      await userToFollow.save();
    }

    console.log('✅ Database seeding completed successfully!');
    console.log(`👥 Created ${createdUsers.length} users`);
    console.log(`🎉 Created ${createdActivities.length} activities`);
    
    // Display summary
    console.log('\n📊 Summary:');
    for (const user of createdUsers) {
      const userActivities = await Activity.countDocuments({ creator: user._id });
      const joinedActivities = await Activity.countDocuments({ 
        'participants.user': user._id,
        'participants.status': 'joined'
      });
      console.log(`${user.nickname}: ${userActivities} created, ${joinedActivities} joined`);
    }

  } catch (error) {
    console.error('❌ Error seeding database:', error);
  } finally {
    await mongoose.connection.close();
    console.log('🔌 Database connection closed');
    process.exit(0);
  }
};

// Run seeding
seedDatabase();